"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '07/09/2022'
    comment: 自定义grid view
"""
import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QSplitter, QVBoxLayout, QHBoxLayout, QSpacerItem, QSizePolicy, QTableView, QApplication
from PyQt5.QtGui import QStandardItemModel
from PyQt5.QtCore import Qt, pyqtSlot
from dataclasses import dataclass

from project.component.basic.user_combobox import UserCombobox
from project.component.basic.user_radio_button import UserRadioButton
from project.component.basic.user_text import UserText


@dataclass
class Component:
    """
    """
    control: UserCombobox | UserRadioButton | UserText
    after_gap: int


@dataclass
class GridViewQuery:
    """
    """
    components: list[list[Component]]


class UserGridView(QWidget):

    def __init__(self,
                 query_components: list[list[Component]],
                 query_button: QPushButton,
                 export_button: QPushButton = None,
                 result_height: int = 630,
                 parent=None):
        """
        """
        super().__init__(parent)

        # 上半部分(条件区)
        self.query_widget = QWidget()
        self.query_v_box = QVBoxLayout(self.query_widget)
        self.layouts = []
        for idx, components in enumerate(query_components):
            layout = QHBoxLayout()
            for component in components:
                layout.addWidget(component.control)
                layout.addItem(QSpacerItem(component.after_gap, 0, QSizePolicy.Fixed, QSizePolicy.Minimum))

            # 最后一行
            if idx == len(query_components) - 1:
                layout.addStretch()
                layout.addWidget(query_button)
                if export_button is not None:
                    layout.addWidget(export_button)
            self.query_v_box.addLayout(layout)
            self.layouts.append(layout)
        self.query_v_box.addStretch()

        # 下半部分(查询区)
        self.result_widget = QWidget()
        self.result_widget.setFixedHeight(result_height)
        self.result_v_box = QVBoxLayout(self.result_widget)

        self.table = QTableView()
        self.model = QStandardItemModel(0, 0)
        self.table.setModel(self.model)
        self.result_v_box.addWidget(self.table)

        self.splitter = QSplitter(Qt.Vertical)
        self.splitter.setHandleWidth(8)  # 手柄宽一点好拖
        self.splitter.setStretchFactor(0, 0)  # 条件区不拉伸
        self.splitter.setStretchFactor(1, 0)  # 结果区占剩余
        self.splitter.setHandleWidth(1)  # 可选：只留视觉线
        self.splitter.setChildrenCollapsible(False)  # 禁止把子窗口折叠成 0 高度
        self.splitter.addWidget(self.query_widget)
        self.splitter.addWidget(self.result_widget)

        # 布局
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)  # 去掉外边距，可自由调整
        layout.addWidget(self.splitter)

    def get_filter(self):
        """ 得到查询组目前的结果集
        :return:
        """
        ret_data = dict()
        for layout in self.layouts:
            for i in range(layout.count()):
                item = layout.itemAt(i)  # QLayoutItem
                widget = item.widget()  # 如果是控件，返回 QWidget；否则 None
                if not widget:
                    continue

                if not isinstance(widget, (UserCombobox, UserRadioButton, UserText)):
                    continue
                object_name = widget.object_name()
                if not object_name:
                    continue
                ret_data[object_name] = widget.text()

        return ret_data


# ----------------- Demo 窗口 -----------------
class DemoWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('GridView Demo')

        # 创建两个自定义组件
        name_edit = UserText('姓名:', '张三', explain_text='这是在测试#{text}的名称', object_name='name')
        age_edit = UserText('年龄:', '18', object_name='age')

        query_button = QPushButton('🔍 查询')
        user_grid_view = UserGridView(
            query_components=[
                [
                    Component(control=name_edit, after_gap=20),
                    Component(control=age_edit, after_gap=0)
                ]
            ],
            query_button=query_button
        )
        query_button.clicked.connect(user_grid_view.get_filter)
        # 整体布局
        main_layout = QVBoxLayout(self)
        main_layout.addWidget(user_grid_view)


# ----------------- main -----------------
if __name__ == '__main__':
    """
    """
    app = QApplication(sys.argv)
    w = DemoWindow()
    w.show()
    sys.exit(app.exec_())

